import { ref, computed } from 'vue'
import { defineStore } from 'pinia'
import { login, register, sendVerifyCode, loginByEmailCode, registerByEmailCode } from '@/api/user'
import { ElMessage } from 'element-plus'
import { useUserProfileStore } from './profile'

export const useAuthStore = defineStore('auth', () => {
  // 存储token
  const token = ref(localStorage.getItem('token') || '')
  
  // 计算是否已认证
  const isAuthenticated = computed(() => !!token.value)
  
  // 登录
  async function loginUser(username, password) {
    try {
      const response = await login({ 
        username, 
        password 
      })
      if (response.status === 0) {
        // 存储token
        token.value = response.data
        localStorage.setItem('token', response.data)
        
        // 获取用户信息
        const userProfileStore = useUserProfileStore()
        await userProfileStore.fetchUserInfo()
        
        ElMessage.success('登录成功')
        return true
      } else {
        ElMessage.error(response.message)
        return false
      }
    } catch (error) {
      console.error('登录失败:', error)
      return false
    }
  }

  // 注册
  async function registerUser(userData) {
    try {
      // 验证必要参数
      if (!userData.username || !userData.password) {
        ElMessage.warning('用户名和密码不能为空')
        return false
      }
      
      // 调用注册API
      const response = await register(userData)
      
      if (response.status === 0) {
        // 注册成功后自动登录
        const loginResponse = await login({
          username: userData.username,
          password: userData.password
        })
        
        if (loginResponse.status === 0) {
          // 登录成功，保存token
          token.value = loginResponse.data
          localStorage.setItem('token', loginResponse.data)
          
          // 获取用户信息
          const userProfileStore = useUserProfileStore()
          await userProfileStore.fetchUserInfo()
          return true
        }
      } else {
        // 注册失败
        ElMessage.error(response.message)
        return false
      }
    } catch (error) {
      console.error('注册失败:', error)
      return false
    }
  }

  // 发送验证码
  async function sendCode(email) {
    try {
      const response = await sendVerifyCode(email)
      if (response.status === 0) {
        ElMessage.success('验证码发送成功')
        return true
      } else {
        ElMessage.error(response.message)
        return false
      }
    } catch (error) {
      console.error('发送验证码失败:', error)
      return false
    }
  }

  // 通过邮箱验证码登录
  async function loginWithEmailCode(userData) {
    try {
      const response = await loginByEmailCode(userData)
      if (response.status === 0) {
        token.value = response.data
        localStorage.setItem('token', response.data)

        // 获取用户信息
        const userProfileStore = useUserProfileStore()
        await userProfileStore.fetchUserInfo()

        return true
      } else {
        ElMessage.error(response.message)
        return false
      }
    } catch (error) {
      console.error('登录失败:', error)
      return false
    }
  }

  // 通过邮箱验证码注册
  async function registerWithEmailCode(userData) {
    try {
      const response = await registerByEmailCode(userData)
      if (response.status === 0) {
        // 注册成功后自动登录
        const loginResponse = await loginWithEmailCode({
          email: userData.email,
          code: userData.code
        })
        
        if (loginResponse.status === 0) {
          // 登录成功，保存token
          token.value = loginResponse.data
          localStorage.setItem('token', loginResponse.data)
          
          // 获取用户信息
          const userProfileStore = useUserProfileStore()
          await userProfileStore.fetchUserInfo()

          return true
        }
      } else {
        ElMessage.error(response.message)
        return false
      }
    } catch (error) {
      console.error('注册失败:', error)
      return false
    }
  }

  // 登出
  function logoutUser() {
    token.value = ''
    localStorage.removeItem('token')
    
    const userProfileStore = useUserProfileStore()
    userProfileStore.clearUserInfo()
    
    ElMessage.success('已退出登录')
  }

  // 检查token是否有效
  async function checkAuth() {
    if (!token.value) return false
    
    try {
      const userProfileStore = useUserProfileStore()
      const userInfo = await userProfileStore.fetchUserInfo()
      return !!userInfo
    } catch (error) {
      console.error('验证失败:', error)
      token.value = ''
      localStorage.removeItem('token')
      return false
    }
  }

  return {
    token,
    isAuthenticated,
    loginUser,
    registerUser,
    logoutUser,
    sendCode,
    loginWithEmailCode,
    registerWithEmailCode,
    checkAuth
  }
}, {
  persist: {
    key: 'user-auth',
    storage: localStorage,
    paths: ['token']
  }
}) 